package com.tdd.api.server.base.util;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.tdd.api.server.base.returns.RespCode;
import com.tdd.api.server.base.returns.RespEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * InterceptorUtil
 *
 * @Author: lvchangbin
 * @Date: 2018/12/27 16:44
 * @Version 1.0
 */
@Slf4j
@Component
public class InterceptorUtil {

    /**
     * ajax返回
     *
     * @param response
     */
    public void ajaxResponse(HttpServletResponse response, RespCode respCode) {
        PrintWriter writer = null;
        try {
            log.warn("ajaxResponse error : " + JSONUtil.toJsonStr(respCode));
            response.setContentType("application/json;charset=utf-8");
            writer = response.getWriter();
            RespEntity respEntity = new RespEntity(respCode);
            writer.write(JSONUtil.toJsonStr(respEntity));
        } catch (Exception var12) {
            log.error("--ajaxResponse error--", var12);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception var11) {
                    log.error("--ajaxResponse close writer error--", var11);
                }
            }
        }
    }

    /**
     * 过滤的协议（http://）的请求路径
     *
     * @param request
     * @return
     */
    public String subtractProtocolFromRequestURL(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        /**内网域名转成公网域名进行处理，后面会用这个url作为key来查询cache和zk**/
        return url.replace("http://", "").replace("https://", "");
    }



    /**
     * 将对象装换为map
     *
     * @param bean
     * @return
     */
    public <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = Maps.newHashMap();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }

}
